

#include "main.h"
#include "assitant.h"
#include "mqtts.h"
#include <IRremoteESP8266.h>
#include <IRrecv.h>

int ir_read_task();
int cmd_ir(int n, char *arg[]);
void ir_pipe_setup(String &pins);
void ir_init();
int _short_beep();

IRrecv *irrecv = NULL;

Pipe ir_input_pipe = NULL;

void ir_init()
{
    public_a_cmd_link("ir", cmd_ir);
}

int cmd_ir(int n, char *args[])
{
    if (n == 1)
    {
        if (irrecv)
        {
            outs("on");
        }
        else
            outs("off");
        return 0;
    }
    String m = String(args[1]);
    if (m == "on")
    {
        if (irrecv)
            return 0;
        if (n > 2)
        {
            String pins(args[2]);
            ir_pipe_setup(pins);
        }
        else
        {
            String pins;
            ir_pipe_setup(pins);
        }
        return 0;
    }
    if (m == "off")
    {
        if (!irrecv)
            return 0;
        irrecv->disableIRIn();
        delete irrecv;
        irrecv = NULL;
        xouts("IR monitor stoped");
        remove_timer(ir_read_task);
        remove_a_pipe(ir_input_pipe, 's');
        ir_input_pipe = NULL;
        return 0;
    }
    outs("usage:ir [[on [pin]]|[off]]");
    return -__LINE__;
}
void ir_pipe_setup(String &pins)
{
    int cast_to_pin(const String &s);
    var pin = cast_to_pin(pins);
    if (pin < 0)
        pin = D5;
    irrecv = new IRrecv(pin);
    if (!irrecv)
        return;
    irrecv->enableIRIn();
    xouts("IR monitor started");
    ir_input_pipe = public_a_new_pipe("ir", irrecv, NULL, 's');
    public_a_timer(ir_read_task, Hz(13));
}

int ir_read_task()
{
    decode_results result;
    if (irrecv->decode(&result))
    {
        var val = result.value;
        irrecv->resume();
        int *p = (int *)(&val);
        if (!result.command)
        {
            if (~val == 0)
            {
                extern int beep_status;
                if (beep_status == 3)
                {
                    int recall_alert_signal();
                    recall_alert_signal();
                    extern int _alert_state;
                    extern long int _last_recall_time;
                    _last_recall_time = millis();
                    _alert_state = 0;
                    return 0;
                }
            }
            if (((p[0]) & 0xffff0000) != 0x800000 && (~val != 0))
                return 0;
        }
        _short_beep();
        pipe_release_data(ir_input_pipe, "ir trigger\n", 12);
    }
    return 0;
}
